package cn.itcast.nio.c5;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static cn.itcast.nio.c1.ByteBufferUtil.debugAll;

/*文件异步io*/
@Slf4j
public class AioFileChannel {
    public static void main(String[] args) throws InterruptedException {
        try ( AsynchronousFileChannel channel=AsynchronousFileChannel.open
                (Paths.get("C:\\Users\\dell\\IdeaProjects\\Netty\\netty-demo\\data.txt"),
                        StandardOpenOption.READ)){
            //参数1.ByteBuffer
            //参数2.读取的起始位置
            //参数3.附件
            //参数4.回调对象
            ByteBuffer buffer=ByteBuffer.allocate(16);
            log.debug("read begin...");
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override  //read成功
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("read completed...{}",result);
                    attachment.flip();
                    debugAll(attachment);
                }

                @Override  //read 失败
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
        log.debug("read end...");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //回调函数是一个守护线程，主线程结束了，守护线程也会结束，所以要让主线程结束后在沉睡几秒，留出给守护线程完成的时间
        Thread.sleep(10000);
    }
}
